package cc.ls5l.tools.base;

import cc.ls5l.tools.constant.EnvEnum;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.setting.Setting;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class DbService {
    // db写操作
    public static Db db;
    private static DataSource ds;

    public static void initDb(EnvEnum enumEnv) {
        switch (enumEnv) {
            case PROD:
                prod();
                break;
            default:
                dev();
                break;
        }
    }

    private static void dev() {
        Setting setting = new Setting("dev.setting");
        //String env = setting.getStr("url");
        //获取指定配置，第二个参数为分组，用于多数据源，无分组情况下传null
        DSFactory dsFactory = DSFactory.create(setting);
        ds = dsFactory.getDataSource();
        db = Db.use(ds);
    }

    private static void prod() {
        //自定义数据库Setting，更多实用请参阅Hutool-Setting章节
        Setting setting = new Setting("prod.setting");
//        String env = setting.getStr("url");
        //获取指定配置，第二个参数为分组，用于多数据源，无分组情况下传null
        ds = DSFactory.create(setting).getDataSource();
        db = Db.use(ds);
    }

    public static int execute(String sql, Object... obj) {
        try {
            int ir = db.execute(sql, obj);
            return ir;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static List<Entity> query(String sql, Object... obj) {
        if (db != null) {
            try {
                return db.query(sql, obj);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static Entity queryOne(String sql, Object... obj) {
        try {
            return db.queryOne(sql, obj);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
